<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('新增大区会长档案')" />
    <th:block th:include="include :: bootstrap-fileinput-css"/>
    <th:block th:include="include :: summernote-css" />
    <link href="../static/css/bootstrap-select.min.css" th:href="@{/css/bootstrap-select.min.css}" rel="stylesheet"/>
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-agentinfo-add">
            <input id="agentImage" name="agentImage" class="form-control" type="hidden" required>
            <input id="agentLicense" name="agentLicense" class="form-control" type="hidden" required>
            <input id="agentProvinceName" name="agentProvinceName" class="form-control" type="hidden">
            <input id="agentCityName" name="agentCityName" class="form-control" type="hidden">
            <input id="agentDistrictName" name="agentDistrictName" class="form-control" type="hidden">
            <input name="rows" type="hidden" id="rows"/>
            <h4 class="form-header h4">大区会长档案信息</h4>
            <div class="row">
                <div class="col-sm-6">
                    <div class="form-group">
                        <label class="col-sm-4 control-label is-required">大区会长名称：</label>
                        <div class="col-sm-8">
                            <input name="agentName" class="form-control" type="text" required>
                        </div>
                    </div>
                </div>
                <div class="col-sm-6">
                    <div class="form-group">
                        <label class="col-sm-4 control-label is-required">登录密码：</label>
                        <div class="col-sm-8">
                            <div class="input-group">
                                <input id="agentPassword" name="agentPassword" placeholder="请输入登录密码" class="form-control" type="password" th:value="${@config.getKey('sys.user.initPassword')}" required>
                                <span class="input-group-addon" title="登录密码,鼠标按下显示密码"
                                      onmousedown="$('#factoryPassword').attr('type','text')"
                                      onmouseup="$('#factoryPassword').attr('type','password')"><i class="fa fa-key"></i></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-6">
                    <div class="form-group">
                        <label class="col-sm-4 control-label is-required">大区会长联系人：</label>
                        <div class="col-sm-8">
                            <input name="agentPerson" class="form-control" type="text" required>
                        </div>
                    </div>
                </div>
                <div class="col-sm-6">
                    <div class="form-group">
                        <label class="col-sm-4 control-label is-required">大区会长联系方式：</label>
                        <div class="col-sm-8">
                            <input name="agentPhone" class="form-control" type="text" required>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-6">
                    <label class="col-sm-4 control-label is-required">所在区域：</label>
                    <div class="col-sm-8">
                        <select class="selectpicker form-control" onchange="initCity()" id="agentProvince" name="agentProvince" required>
                            <option value="">&#45;&#45;省份&#45;&#45;</option>
                        </select>
                        <select class="selectpicker form-control" onchange="initRegion()" id="agentCity" name="agentCity" required>
                            <option value="">&#45;&#45;城市&#45;&#45;</option>
                        </select>
                        <select class="selectpicker form-control" id="agentDistrict" name="agentDistrict" required>
                            <option value="">&#45;&#45;县区&#45;&#45;</option>
                        </select>
                    </div>
                </div>
                <div class="col-sm-6">
                    <div class="form-group">
                        <label class="col-sm-4 control-label is-required">详细地址：</label>
                        <div class="col-sm-8">
                            <input name="agentAddress" class="form-control" type="text" required>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-6">
                    <div class="form-group">
                        <label class="col-sm-4 control-label is-required">身份证：</label>
                        <div class="col-sm-8">
                            <input name="agentCard" class="form-control" type="text" required>
                        </div>
                    </div>
                </div>
                <!--<div class="col-sm-6">
                    <div class="form-group">
                        <label class="col-sm-4 control-label">服务承诺：</label>
                        <div class="col-sm-8">
                            <input name="agentService" class="form-control" type="text">
                        </div>
                    </div>
                </div>-->
                <div class="col-sm-6">
                    <div class="form-group">
                        <label class="col-sm-4 control-label">店铺浏览量：</label>
                        <div class="col-sm-8">
                            <input name="agentPageviews" class="form-control" type="text">
                        </div>
                    </div>
                </div>
            </div>
            <!--<div class="row">
                <div class="col-sm-6">
                    <div class="form-group">
                        <label class="col-sm-4 control-label">主营产品：</label>
                        <div class="col-sm-8">
                            <textarea name="agentContent" class="form-control"></textarea>
                        </div>
                    </div>
                </div>

            </div>-->
            <div class="row">
                <div class="col-sm-6">
                    <div class="form-group">
                        <label class="col-sm-4 control-label is-required">门头图片：</label>
                        <div class="col-sm-8">
                            <p class="user-info-head" onclick="avatar()"><img id="agentImageShow" class="img-thumbnail img-lg" ></p>
                            <!--<input type="hidden" name="agentImage">
                            <div class="file-loading">
                                <input class="form-control file-upload" id="agentImage" name="file" type="file">
                            </div>-->
                        </div>
                    </div>

                </div>
                <div class="col-sm-6">
                    <div class="form-group">
                        <label class="col-sm-4 control-label is-required">营业执照：</label>
                        <div class="col-sm-8">
                            <p class="user-info-head" onclick="avatarLicense()"><img id="agentLicenseShow" class="img-thumbnail img-lg" ></p>
                            <!--<input type="hidden" name="agentLicense">
                            <div class="file-loading">
                                <input class="form-control file-upload" id="agentLicense" name="file" type="file">
                            </div>-->
                        </div>
                    </div>
                </div>
            </div>
            <!--<div class="form-group">
                <label class="col-sm-3 control-label">有效状态：</label>
                <div class="col-sm-8">
                    <div class="radio-box" th:each="dict : ${@dict.getType('validate_state')}">
                        <input type="radio" th:id="${'agentValid_' + dict.dictCode}" name="agentValid" th:value="${dict.dictValue}" th:checked="${dict.default}">
                        <label th:for="${'agentValid_' + dict.dictCode}" th:text="${dict.dictLabel}"></label>
                    </div>
                </div>
            </div>-->
            <h4 class="form-header h4">大区会长管辖区域信息</h4>
            <div class="row">
                <div class="col-sm-12">
                    <button type="button" class="btn btn-white btn-sm" onclick="addColumn()"><i class="fa fa-plus"> 增加</i></button>
                    <button type="button" class="btn btn-white btn-sm" onclick="sub.delColumn()"><i class="fa fa-minus"> 删除</i></button>
                    <div class="col-sm-12 select-table table-striped">
                        <table id="bootstrap-table"></table>
                    </div>
                </div>
            </div>
        </form>
    </div>
    <div class="row">
        <div class="col-sm-offset-5 col-sm-10">
            <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()"><i class="fa fa-check"></i>保 存</button>&nbsp;
            <button type="button" class="btn btn-sm btn-danger" onclick="closeItem()"><i class="fa fa-reply-all"></i>关 闭 </button>
        </div>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: bootstrap-fileinput-js"/>
    <th:block th:include="include :: summernote-js" />
    <script src="../static/js/bootstrap-select.min.js" th:src="@{/js/bootstrap-select.min.js}"></script>
    <script th:inline="javascript">
        var prefix = ctx + "zsyh/agentinfo"
        $("#form-agentinfo-add").validate({
            focusCleanup: true
        });

        function submitHandler() {
            if ($.validate.form()) {
                $("#agentProvinceName").val($('#agentProvince option:selected').text());
                $("#agentCityName").val($('#agentCity option:selected').text());
                $("#agentDistrictName").val($('#agentDistrict option:selected').text());
                $.operate.save(prefix + "/add", $('#form-agentinfo-add').serialize());
            }
        }

        $(".file-upload").fileinput({
            uploadUrl: ctx + 'common/uploadOSS',
            maxFileCount: 1,
            autoReplace: true
        }).on('fileuploaded', function (event, data, previewId, index) {
            $("input[name='" + event.currentTarget.id + "']").val(data.response.url)
        }).on('fileremoved', function (event, id, index) {
            $("input[name='" + event.currentTarget.id + "']").val('')
        })

        $(function() {
            var options = {
                pagination: false,
                showSearch: false,
                showRefresh: false,
                showToggle: false,
                showColumns: false,
                sidePagination: "client",
                columns: [{
                    checkbox: true
                },
                {
                    field: 'index',
                    align: 'center',
                    title: "序号",
                    formatter: function (value, row, index) {
                    	var columnIndex = $.common.sprintf("<input type='hidden' name='index' value='%s'>", $.table.serialNumber(index));
                    	var agentProvince = $.common.sprintf("<input class='form-control' type='hidden' name='zsyhAgentAreaList[%s].agentProvince' value='%s'>", index, row.agentProvince);
                    	var agentCity = $.common.sprintf("<input class='form-control' type='hidden' name='zsyhAgentAreaList[%s].agentCity' value='%s'>", index, row.agentCity);
                    	var agentDistrict = $.common.sprintf("<input class='form-control' type='hidden' name='zsyhAgentAreaList[%s].agentDistrict' value='%s'>", index, row.agentDistrict);
                    	return columnIndex + $.table.serialNumber(index)+agentProvince+agentCity+agentDistrict;
                    }
                },
                /*{
                    field: 'agentProvince',
                    align: 'center',
                    title: '管辖区域省级代码',
                    formatter: function(value, row, index) {
                        var html = $.common.sprintf("<input class='form-control' type='text' name='zsyhAgentAreaList[%s].agentProvince' value='%s'>", index, value);
                        return html;
                    }
                },*/
                {
                    field: 'agentProvinceName',
                    align: 'center',
                    title: '省级名称',
                    formatter: function(value, row, index) {
                        var html = $.common.sprintf("<input class='form-control' style='text-align: center' placeholder='请单击选择管辖区域' type='text' onclick='provinceSelect(\""+index+"\")' name='zsyhAgentAreaList[%s].agentProvinceName' value='%s' readonly>", index, value);
                        return html;
                    }
                },
                /*{
                    field: 'agentCity',
                    align: 'center',
                    title: '管辖区域城市代码',
                    formatter: function(value, row, index) {
                        var html = $.common.sprintf("<input class='form-control' type='text' name='zsyhAgentAreaList[%s].agentCity' value='%s'>", index, value);
                        return html;
                    }
                },*/
                {
                    field: 'agentCityName',
                    align: 'center',
                    title: '城市名称',
                    formatter: function(value, row, index) {
                        var html = $.common.sprintf("<input class='form-control' style='text-align: center'  type='text' name='zsyhAgentAreaList[%s].agentCityName' value='%s' readonly>", index, value);
                        return html;
                    }
                },
                /*{
                    field: 'agentDistrict',
                    align: 'center',
                    title: '管辖区域县区代码',
                    formatter: function(value, row, index) {
                        var html = $.common.sprintf("<input class='form-control' type='text' name='zsyhAgentAreaList[%s].agentDistrict' value='%s'>", index, value);
                        return html;
                    }
                },*/
                {
                    field: 'agentDistrictName',
                    align: 'center',
                    title: '县区名称',
                    formatter: function(value, row, index) {
                        var html = $.common.sprintf("<input class='form-control' style='text-align: center'  type='text' name='zsyhAgentAreaList[%s].agentDistrictName' value='%s' readonly>", index, value);
                        return html;
                    }
                },
               ]
            };
            $.table.init(options);
        });

        function addColumn() {
            var count = $("#" + table.options.id).bootstrapTable('getData').length;
            sub.editColumn();
        	
            $("#" + table.options.id).bootstrapTable('insertRow', {
                index: count,
                row: {
                    index: $.table.serialNumber(count),
                    agentProvince: "",
                    agentProvinceName: "",
                    agentCity: "",
                    agentCityName: "",
                    agentDistrict: "",
                    agentDistrictName: "",
                }
            });
        }

        function addTableColumn(){
            var rows = $("#rows").val();
            var data = JSON.parse(rows);
            var count = $("#bootstrap-table").bootstrapTable('getData').length;
            var oldRow = $("#bootstrap-table").bootstrapTable('getData');
            var existArr = new Array();
            var noexistArr = new Array();
            var existStr="";
            var noexistStr="";
            var provinceArray = new Array();
            var cityArray = new Array();
            var districtArray = new Array();
            for(var i=0;i<data.length;i++){
                if(data[i].level == 0){
                    provinceArray.push(data[i]);
                }
                if(data[i].level == 1){
                    cityArray.push(data[i]);
                }
                if(data[i].level == 2){
                    districtArray.push(data[i]);
                }
            }
            var cityTempArray = new Array();
            for(var j=0;j<cityArray.length;j++){
                for(var n=0;n<provinceArray.length;n++){
                    if(cityArray[j].pId == provinceArray[n].id){
                        break;
                    }
                }
                var temp = {provinceId:provinceArray[n].id,provinceName:provinceArray[n].name,cityId:cityArray[j].id,cityName:cityArray[j].name};
                cityTempArray.push(temp);
            }
            var districtTempArray =new Array();
            for(var j=0;j<districtArray.length;j++){
                for(var n=0;n<cityTempArray.length;n++){
                    if(districtArray[j].pId == cityTempArray[n].cityId){
                         break;
                    }
                }
                var temp ={provinceId:cityTempArray[n].provinceId,provinceName:cityTempArray[n].provinceName,cityId:cityTempArray[n].cityId,cityName:cityTempArray[n].cityName,districtId:districtArray[j].id,districtName:districtArray[j].name};
                districtTempArray.push(temp);
            }
            if(districtTempArray.length>1) {
                for (var j = 0; j < districtTempArray.length; j++) {
                    //判断是否存在同样的区域，如果存在则不能重复添加
                    var flag = false;
                    for (var m = 0; m < oldRow.length; m++) {
                        if (oldRow[m].agentProvince == districtTempArray[j].provinceId && oldRow[m].agentCity == districtTempArray[j].cityId && oldRow[m].agentDistrict == districtTempArray[j].districtId) {
                            flag = true;
                            break;
                        }
                    }
                    if (flag) {
                        existStr = existStr + j + ",";
                    } else {
                        noexistStr = noexistStr + j + ",";
                    }
                }
                existArr = existStr.substr(0,existStr.length-1).split(",");
                noexistArr = noexistStr.substr(0,noexistStr.length-1).split(",");
                //如果有不重复的产品
                if (noexistArr.length>0) {
                    //更新当前行
                    $('#bootstrap-table').bootstrapTable('updateRow', {
                        index: currIndex,
                        row: {
                            agentProvince: districtTempArray[noexistArr[0]].provinceId,
                            agentProvinceName: districtTempArray[noexistArr[0]].provinceName,
                            agentCity: districtTempArray[noexistArr[0]].cityId,
                            agentCityName: districtTempArray[noexistArr[0]].cityName,
                            agentDistrict: districtTempArray[noexistArr[0]].districtId,
                            agentDistrictName: districtTempArray[noexistArr[0]].districtName,
                        }
                    });
                    //添加剩余行
                    for(var m=1;m<noexistArr.length;m++) {
                        currIndex++;
                        $("#bootstrap-table").bootstrapTable('insertRow', {
                            index: count +m -1,
                            row: {
                                index: $.table.serialNumber(count +m -2),

                                agentProvince: districtTempArray[noexistArr[m]].provinceId,
                                agentProvinceName: districtTempArray[noexistArr[m]].provinceName,
                                agentCity: districtTempArray[noexistArr[m]].cityId,
                                agentCityName: districtTempArray[noexistArr[m]].cityName,
                                agentDistrict: districtTempArray[noexistArr[m]].districtId,
                                agentDistrictName: districtTempArray[noexistArr[m]].districtName,
                            },
                        });
                    }
                }
            }else{
                //判断是否存在同类产品，如果存在则不能重复添加
                var flag = false;
                for (var m = 0; m < oldRow.length; m++) {
                    if (oldRow[m].agentProvince == districtTempArray[0].provinceId && oldRow[m].agentCity == districtTempArray[0].cityId && oldRow[m].agentDistrict == districtTempArray[0].districtId) {
                        flag = true;
                        break;
                    }
                }
                if(!flag){
                    //如果选中一行，则更新
                    $('#bootstrap-table').bootstrapTable('updateRow', {
                        index: currIndex,
                        row: {

                            agentProvince: districtTempArray[0].provinceId,
                            agentProvinceName: districtTempArray[0].provinceName,
                            agentCity: districtTempArray[0].cityId,
                            agentCityName: districtTempArray[0].cityName,
                            agentDistrict: districtTempArray[0].districtId,
                            agentDistrictName: districtTempArray[0].districtName,
                        }
                    });
                }
            }
        }

        $(document).ready(function(){
            // 地区下拉框初始化
            $("#agentProvince").selectpicker({width:130, liveSearch: true, liveSearchPlaceholder: "搜索" });
            $("#agentCity").selectpicker({width:120, liveSearch: true, liveSearchPlaceholder: "搜索" });
            $("#agentDistrict").selectpicker({width:120, liveSearch: true, liveSearchPlaceholder: "搜索" });

            // 动态加载省份选项数据
            initSelectOptions("agentProvince","0");
        });// onReady

        /**
         * 动态生成select选项
         * @param selectId
         * @returns
         */
        function initSelectOptions(selectId,parentId) {
            var selectObj = $("#" + selectId);
            $.ajax({
                url : ctx + "zsyh/factory/"+parentId,
                async : false,
                type : "GET",
                success : function(result) {
                    debugger;
                    var configs = result.rows;
                    selectObj.find("option:not(:first)").remove();
                    for (var i in configs) {
                        var addressConfig = configs[i];
                        var optionValue = addressConfig.id;
                        var optionText = addressConfig.areaName;
                        selectObj.append(new Option(optionText, optionValue));
                    }

                    // 刷新select
                    selectObj.selectpicker('refresh');
                },
                error : function(result) {
                    toastr.error('获取['+ parentId + ']信息失败，原因：' + result.errorMessage);
                }
            });// ajax
        }

        /**
         * 根据选择的省份动态初始化城市options
         * @returns
         */
        function initCity() {
            // 当省份变动时，初始化城市和清空县区和街道
            var provinceSel = $("#agentProvince").val();
            initSelectOptions("agentCity", provinceSel);
            $("#agentDistrict").find("option:not(:first)").remove();
            $("#agentDistrict").selectpicker('refresh');
        }

        /**
         * 根据选择的城市动态初始化区域options
         * @returns
         */
        function initRegion() {
            // 选择城市
            var citySel = $("#agentCity").val();
            initSelectOptions("agentDistrict", citySel);
        }

        /*门头管理*/
        function avatar() {
            var url = ctx + 'zsyh/agentinfo/avatar?agentImage='+$("#agentImage").val();
            layer.open({
                type: 2,
                area: [$(window).width()/2 + 'px', $(window).height() + 'px'],
                fix: false,
                //不固定
                maxmin: true,
                shade: 0.3,
                title: "上传门头图片",
                content: url,
                btn: ['确定', '关闭'],
                // 弹层外区域关闭
                shadeClose: true,
                yes: function(index, layero) {
                    debugger;
                    var iframeWin = layero.find('iframe')[0];
                    var imageUrl = layero.find('iframe')[0].contentWindow.$("#imageUrl").val();
                    //执行子页面的方法
                    iframeWin.contentWindow.submitHandler(index, layero);
                },
                cancel: function(index) {
                    return true;
                }
            });
        }

        /*营业执照管理*/
        function avatarLicense() {
            var url = ctx + 'zsyh/agentinfo/avatarLicense?agentLicense='+$("#agentLicense").val();
            layer.open({
                type: 2,
                area: [$(window).width()/2 + 'px', $(window).height() + 'px'],
                fix: false,
                //不固定
                maxmin: true,
                shade: 0.3,
                title: "上传门头图片",
                content: url,
                btn: ['确定', '关闭'],
                // 弹层外区域关闭
                shadeClose: true,
                yes: function(index, layero) {
                    debugger;
                    var iframeWin = layero.find('iframe')[0];
                    var imageUrl = layero.find('iframe')[0].contentWindow.$("#imageUrl").val();
                    iframeWin.contentWindow.submitHandler(index, layero);
                },
                cancel: function(index) {
                    return true;
                }
            });
        }

        function provinceSelect(index) {
            currIndex =index;
            /*$.modal.open("选择管辖区域", ctx+"warehouse/parts/view/"+$("#orderUserId").val(),1200,800);*/
            var options = {
                title: '管辖区域选择',
                width: "380",
                url: ctx + "zsyh/area/selectAreaTreeShow/",
                callBack: doSubmit
            };
            $.modal.openOptions(options);
        }
        function doSubmit(index, layero){
            debugger;
            var body = layer.getChildFrame('body', index);
            var iframeWin = window[layero.find('iframe')[0]['name']];
            iframeWin.getSelected();
            layer.close(index);
        }
    </script>
</body>
</html>